package com.ptswitch.material.service.impl;

import java.util.List;

import org.hxzon.project.AbstractModelService;
import org.hxzon.util.OgnlUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.base.Upload;
import com.ptswitch.material.model.common.HLog;
import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.service.HLogService;
import com.ptswitch.material.util.MaterialUtil;

@Service
public class HLogServiceImpl extends AbstractModelService<HLog> implements HLogService {

    public List<HLog> findLike(String like, long first, long size) {
        return dao.findLike(HLog.class, like, first, size);
    }

    public void log(String username, String overview, String message) {
        HLog log = new HLog();
        log.setUsername(username);
        log.setOverview(overview);
        if (message.length() > 2048) {
            message = message.substring(0, 2048);
        }
        log.setMessage(message);
//		log.setCreateTime(DateUtils.format(new Date()));
        save(log);
    }

    public void log(Uzer user, String overview, String message) {
        log(user.getUsername(), overview, message);
    }

    public void log(Uzer user, String overview, Object o) {
        StringBuilder message = null;
        if (o instanceof Material) {
            message = MaterialUtil.buildMessage((Material) o);
        } else if (o instanceof Bom) {
            message = MaterialUtil.buildMessage((Bom) o);
        } else if (o instanceof Uzer) {
            message = MaterialUtil.buildMessage((Uzer) o);
        } else if (o instanceof Upload) {
            message = MaterialUtil.buildMessage((Upload) o);
        } else if (o instanceof Contract) {
            message = MaterialUtil.buildMessage((Contract) o);
        } else if (o instanceof String) {
            message = new StringBuilder((String) o);
        } else if (o != null) {
            message = new StringBuilder();
            for (String property : OgnlUtil.getAllStringProperty(o.getClass())) {
                message.append(property + ":" + OgnlUtil.getStringValueOrEmpty(o, property) + ";");
            }
        }
        log(user.getUsername(), overview, message == null ? "" : message.toString());
    }

    public void log(Uzer user, String overview) {
        log(user, overview, (Object) null);
    }

}
